import re

import pymysql

from store.BaseStore import BaseStore
from notify.item.XiaoquChangeItem import XiaoquChangeItem
import datetime
from lib.utility.log import *

class XiaoquStore(BaseStore):


    def get_by_id(self,xiaoqu_id):
        select_sql = "select * from xiaoqu_info where xiaoqu_id=%s" % xiaoqu_id
        cursor = self.execute(select_sql)
        return cursor.fetchone()

    # @staticmethod
    def insertXiaoqu(self,xiaoqu):
        result = self.get_by_id(xiaoqu.xiaoqu_id)
        if not result or result is None:
            self.doInsert(xiaoqu)
            return
        if int(result["online_house_num"]) != int(xiaoqu.on_sale):
            logger.info("新的房源数量:{0}。旧的:{1}".format(xiaoqu.on_sale,result["online_house_num"]))
            #发变化通知
            xiaoqu_change = XiaoquChangeItem(result, xiaoqu)
            #self.notify.notify_xiaoqu_change(xiaoqu_change)
            #更新数据
            self.doUpdate(xiaoqu)

    def doInsert(self,xiaoqu):
        sql = ("insert into xiaoqu_info(`district`,`xuequ_id`,`xiaoqu_id`,`name`,`online_house_num`,`avg_price`,"
               "`description`,`create_time`,`update_time`,`has_sold_num`)"
               " values ('%s','%s','%s','%s',%d,'%s','%s','%s','%s',%d)") % (
            xiaoqu.district,xiaoqu.area,xiaoqu.xiaoqu_id,xiaoqu.name,int(xiaoqu.on_sale),xiaoqu.price,
            xiaoqu.desc,datetime.datetime.now(),datetime.datetime.now(), self.deal_desc(xiaoqu.desc)
        )
        logger.info(sql)
        cursor = self.execute(sql)
        print(cursor.rowcount)

    def doUpdate(self,xiaoqu):
        sql = "update xiaoqu_info set online_house_num=%s,avg_price='%s' where xiaoqu_id='%s'" % (xiaoqu.on_sale,xiaoqu.price,xiaoqu.xiaoqu_id)
        cursor = self.execute(sql)
        return cursor.rowcount

    def set_like(self,xiaoqu_id,is_like):
        sql = "update xiaoqu_info set `like`=%d,update_time='%s' where xiaoqu_id='%s'" % (is_like,datetime.datetime.now(),xiaoqu_id)
        self.execute(sql)

    #解析描述，将售出情况统计出来
    def deal_desc(self,description):
        description = description.split("|")
        for i in range(len(description)):
            if "成交" in description[i]:
                #成交套数
                count = re.findall(r"\d+", description[i])[1]
                return int(count)
        return 0

    #刷新售出数量
    def flush_sold_num(self, xiaoqu_id):
        xiaoqu = self.get_by_id(xiaoqu_id)
        desc = xiaoqu["description"]
        desc = self.deal_desc(desc)
        sql = "update xiaoqu_info set `has_sold_num`=%d,update_time='%s' where xiaoqu_id='%s'" % (
        desc, datetime.datetime.now(), xiaoqu_id)
        logger.info("成交数量刷新完毕:{0}".format(xiaoqu_id))
        self.execute(sql)

    def get_all(self):
        select_sql = "select * from xiaoqu_info"
        cursor = self.execute(select_sql)
        return cursor.fetchall()

    def flush_all_sold(self):
        data = self.get_all()
        [self.flush_sold_num(x["xiaoqu_id"]) for x in data]

    def get_all_like_house(self):
        select_sql = "select * from xiaoqu_info where `like`=1"
        cursor = self.execute(select_sql)
        return cursor.fetchall()

    def query(self,district=None,area=None,id_list=[],name=None,min_price=0,max_price=30):
        sql = "select * from xiaoqu_info where avg_price > %s and avg_price < %s "
        param = [min_price,max_price]
        if district is not None:
            sql += " and district='%s' "
            param.append(district)
        if area is not None:
            sql += " and xuequ_id='%s' "
            param.append(area)

        if len(id_list) > 0:
            sql += "and xiaoqu_id in (" + ",".join(["'%s'" for i in range(len(id_list))]) + ")"
            [param.append(i) for i in id_list]
        if name is not None:
            sql += "and name like '%s' "
            param.append(name+"%")
        sql = sql % tuple(param)
        logger.info(sql)
        return self.execute(sql).fetchall()

if __name__ == "__main__":
    s= "共156个户型|30天成交1套|7套正在出租"
    s= "30天成交1套|11套正在出租"
    x = XiaoquStore()
    print(x.flush_all_sold())